package com.example.distschedule.slice;
/*
 * Copyright (C) [张兵]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.distschedule.ResourceTable;
import com.example.distschedule.bean.Command;
import com.example.distschedule.bean.DeviceResult;
import com.example.distschedule.bean.RespondBase;
import com.example.distschedule.event.MessageEvent;
import com.example.distschedule.rx2.OKHttpUtilsRx2;
import com.example.distschedule.toast.XToastUtils;
import com.example.distschedule.utils.CommandUtil;
import com.example.distschedule.utils.DeviceStateUtil;
import com.example.distschedule.utils.PreferencesUtil;
import com.socks.library.KLog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.miscservices.timeutility.Time;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.greenrobot.eventbus.EventBus;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.Locale;
import java.util.Map;

import static com.example.distschedule.slice.SelectDeviceAbilitySlice.KEY_IS_SET_COMMAND;

/**
 * 智能语音垃圾桶控制页面Dustbin
 *
 * @since 2022-2-20
 */
public class DustbinAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private boolean isAlertDustbinON = false;
    private DirectionalLayout commonDustbinControl;
    private DirectionalLayout alertDustbinControl;
    private Image logoDustbinImg;
    private Image SwitchImg_R;
    private Image SwitchImg_U;
    private Image SwitchImg_K;
    private Image SwitchImg_O;
    private String deviceId;
    private Text currentDustbinRValue;
    private Text currentDustbinUValue;
    private Text currentDustbinKValue;
    private Text currentDustbinOValue;

    private boolean isSetCommand = false;
    private boolean isONR = false;
    private boolean isONU = false;
    private boolean isONK = false;
    private boolean isONO = false;

    Image Recyclables;
    Image Unrecyclable;
    Image KitchenGarbage;
    Image OtherRubbish;
    Text Recyclables_Capacity;
    Text Unrecyclable_Capacity;
    Text KitchenGarbage_Capacity;
    Text OtherRubbish_Capacity;

    @Override
    public void onStart(Intent intent){
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_dustbin);
        //找到图片组件
        Recyclables = (Image) findComponentById(ResourceTable.Id_dustbin_Recyclables_image_switch);
        Unrecyclable = (Image) findComponentById(ResourceTable.Id_dustbin_Unrecyclable_image_switch);
        KitchenGarbage = (Image) findComponentById(ResourceTable.Id_dustbin_KitchenGarbage_image_switch);
        OtherRubbish = (Image) findComponentById(ResourceTable.Id_dustbin_OtherRubbish_image_switch);

        deviceId = intent.getStringParam("deviceId");
        isSetCommand = intent.getBooleanParam(KEY_IS_SET_COMMAND, false);
        initComponents();

        initDeviceState();
        initDustbinState();
        //huaweicould(appID);
    }
      private void initDeviceState() {
         KLog.i("[220207x01]initDevice");
         OKHttpUtilsRx2.INSTANCE.getApi().getDeviceInfo(deviceId, PreferencesUtil.getUserId(getContext()))
                 .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                 .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase<DeviceResult>>() {
                     @Override
                     public void onNext(RespondBase<DeviceResult> deviceInfo) {
                         KLog.i(deviceInfo);
                         if(deviceInfo.isSuccess()){
                             KLog.i("isSuccess");
                         }
                         if (deviceInfo.isSuccess() && deviceInfo.getResult().isOnline()) {
                             // 更新状态
                             String property = deviceInfo.getResult().getProperty();

                             KLog.i(property);

                             String value_RC = DeviceStateUtil.getKeyValue(property, "Recyclables_Capacity");
                             String value_UC = DeviceStateUtil.getKeyValue(property, "Unrecyclable_Capacity");
                             String value_KC = DeviceStateUtil.getKeyValue(property, "KitchenGarbage_Capacity");
                             String value_OC = DeviceStateUtil.getKeyValue(property, "OtherRubbish_Capacity");
                             if (value_RC.equals("100")||value_UC.equals("100")||value_KC.equals("100")||value_OC.equals("100")) {
                                 // 告警页面
                                 KLog.i("Alert Dustbin");
                                 isAlertDustbinON = true;
                                 goToAlert();
                             }
                             currentDustbinRValue.setText(String.format("%s", value_RC));
                             currentDustbinUValue.setText(String.format("%s", value_UC));
                             currentDustbinKValue.setText(String.format("%s", value_KC));
                             currentDustbinOValue.setText(String.format("%s", value_OC));

                         } else {
                             initDustbinState();
                         }
                     }

                     @Override
                     public void onError(Throwable throwable) {
                         initDustbinState();
                     }
                 });
     }//初始化垃圾桶状态

    private void initDustbinState() {
        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.asyncDispatch(() -> {
            KLog.i("async task initDustbinState run");

            checkDeviceNet();
        });
    }//初始化垃圾桶状态
    private void checkDeviceNet() {
        Time.sleep(10 * 1000);
        OKHttpUtilsRx2.INSTANCE.getApi().getDeviceInfo(deviceId, PreferencesUtil.getUserId(getContext()))
                .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase<DeviceResult>>() {
                    @Override
                    public void onNext(RespondBase<DeviceResult> deviceInfo) {
                        super.onNext(deviceInfo);
                        KLog.i(deviceInfo);
                        if (deviceInfo.getResult() == null || !deviceInfo.getResult().isOnline()) {
                            XToastUtils.toast("未配网成功，请再次碰一碰重试");
                        }
                    }
                });
    }//检测设备网络

    private void initComponents() {
        SwitchImg_R = (Image) findComponentById(ResourceTable.Id_dustbin_Recyclables_image_switch);
        SwitchImg_U = (Image) findComponentById(ResourceTable.Id_dustbin_Unrecyclable_image_switch);
        SwitchImg_K = (Image) findComponentById(ResourceTable.Id_dustbin_KitchenGarbage_image_switch);
        SwitchImg_O = (Image) findComponentById(ResourceTable.Id_dustbin_OtherRubbish_image_switch);

        logoDustbinImg = (Image) findComponentById(ResourceTable.Id_dustbin_image_logo);
        commonDustbinControl = (DirectionalLayout) findComponentById(ResourceTable.Id_dustbin_common_show);
        alertDustbinControl = (DirectionalLayout) findComponentById(ResourceTable.Id_dustbin_alert_show);

        findComponentById(ResourceTable.Id_dustbin_image_alert_stop).setClickedListener(component -> switchListener());

        findComponentById(ResourceTable.Id_dustbin_img_left).setClickedListener(this::goBack);
        findComponentById(ResourceTable.Id_dustbin_img_right).setClickedListener(this::goInfo);
        currentDustbinRValue = (Text) findComponentById(ResourceTable.Id_dustbin_current_valueR);
        currentDustbinUValue = (Text) findComponentById(ResourceTable.Id_dustbin_current_valueU);
        currentDustbinKValue = (Text) findComponentById(ResourceTable.Id_dustbin_current_valueK);
        currentDustbinOValue = (Text) findComponentById(ResourceTable.Id_dustbin_current_valueO);

        findComponentById(ResourceTable.Id_dustbin_Recyclables_image_switch).setClickedListener(this::Recyclables);
        findComponentById(ResourceTable.Id_dustbin_Unrecyclable_image_switch).setClickedListener(this::Unrecyclable);
        findComponentById(ResourceTable.Id_dustbin_KitchenGarbage_image_switch).setClickedListener(this::KitchenGarbage);
        findComponentById(ResourceTable.Id_dustbin_OtherRubbish_image_switch).setClickedListener(this::OtherRubbish);

    }//初始化组件

    //切换告警页面
    private void goToAlert() {
        logoDustbinImg.setPixelMap(ResourceTable.Media_icon_device_alert);
        commonDustbinControl.setVisibility(Component.HIDE);
        alertDustbinControl.setVisibility(Component.VISIBLE);

    }

    private void saveCommand(Component component) {
        // 将device和命令使用EventBus传出到 SelectDeviceAbilitySlice中，用于保存命令
        EventBus.getDefault().post(new MessageEvent(MessageEvent.EVENT_GET_COMMAND,
                deviceId, CommandUtil.Dustbin_OpenRecyclables_Command(isONR)));
        onBackPressed();
    }

    private void goBack(Component component) {
        onBackPressed();
    }
    private void Recyclables(Component component) {
        isONR = !isONR;
        if (isONR) { ;
            SwitchImg_R.setPixelMap(ResourceTable.Media_icon_switch_on);
        } else {
            SwitchImg_R.setPixelMap(ResourceTable.Media_icon_switch_off);
        }
        // 发送命令
        if (!isSetCommand) {
            sendCommand(CommandUtil.Dustbin_OpenRecyclables_Command(isONR));
        }//Recyclables
    }
    private void Unrecyclable(Component component) {
        isONU = !isONU;
        if (isONU) {
            SwitchImg_U.setPixelMap(ResourceTable.Media_icon_switch_on);
        } else {
            SwitchImg_U.setPixelMap(ResourceTable.Media_icon_switch_off);
        }
        // 是设置日程命令还是发送命令
        if (!isSetCommand) {
            sendCommand(CommandUtil.Dustbin_OpenUnrecyclable_Command(isONU));
        }//Unrecyclable
    }
    private void KitchenGarbage(Component component) {

        isONK = !isONK;
        if (isONK) {
            SwitchImg_K.setPixelMap(ResourceTable.Media_icon_switch_on);
        } else {
            SwitchImg_K.setPixelMap(ResourceTable.Media_icon_switch_off);
        }
        // 是设置日程命令还是发送命令
        if (!isSetCommand) {
            sendCommand(CommandUtil.Dustbin_OpenKitchenGarbage_Command(isONK));
        }//KitchenGarbage
    }
    private void OtherRubbish(Component component) {
        isONO = !isONO;
        if (isONO) {
            SwitchImg_O.setPixelMap(ResourceTable.Media_icon_switch_on);
        } else {
            SwitchImg_O.setPixelMap(ResourceTable.Media_icon_switch_off);
        }
        // 是设置日程命令还是发送命令
        if (!isSetCommand) {
            sendCommand(CommandUtil.Dustbin_OpenOtherRubbish_Command(isONO));
        }//OtherRubbish
    }

    private void goInfo(Component component) {
        XToastUtils.info("接受垃圾桶满了的告警消息，关闭告警", 5000);
    }

    private void switchListener() {
        isAlertDustbinON = !isAlertDustbinON;
        if (!isAlertDustbinON) {
            //回到正常控制页面
            logoDustbinImg.setPixelMap(ResourceTable.Media_icon_trash_can);
            commonDustbinControl.setVisibility(Component.VISIBLE);
            alertDustbinControl.setVisibility(Component.HIDE);
        }

    }

    private void sendCommand(Command command) {
        JSONObject body = new JSONObject();
        body.put("commandName", command.getCommandName());
        body.put("serviceId", command.getServiceId());
        body.put("value", command.getValue());
        OKHttpUtilsRx2.INSTANCE.getApi().sendCommand(deviceId,
                RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), JSON.toJSONString(body)))
                .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase>() {
                    @Override
                    public void onNext(RespondBase respond) {
                        super.onNext(respond);
                        if (respond.isSuccess()) {
                            XToastUtils.toast("控制命令发送成功");
                        }
                    }
                });
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {

    }

}


